<template>
  <div class="ebook-reader">
    <div id="read">
    </div>
  </div>
</template>

<script>
  import Epub from 'epubjs'
  import { EbookMixin } from '../../utils/mixin'
  global.ePub = Epub
  export default {
    name: 'EbookReader',
    mixins: [EbookMixin],
    mounted () {
      // const fileName = this.$route.params.fileName
      // console.log(this.fileName)
      this.initEpub()
    },
    methods: {
      initEpub () {
        // 初始化阅读器
        this.book = new Epub('/2018_Book_AgileProcessesInSoftwareEngine.epub')
        // this.book = new Epub('/皮囊.epub')
        this.setCurrentBook(this.book)
        this.rendition = this.book.renderTo('read', {
          width: innerWidth,
          height: innerHeight
          // 兼容iOS
          // method: 'default'
        })
        this.rendition.display()
        // 手势开始
        this.rendition.on('touchstart', event => {
          this.touchStartX = event.changedTouches[0].clientX
          this.touchStartTime = event.timeStamp
          // event.preventDefault()
          // event.stopPropagation()
        })
        // 手势结束
        this.rendition.on('touchend', event => {
          const offsetX = event.changedTouches[0].clientX - this.touchStartX
          const time = event.timeStamp - this.touchStartTime
          if (time < 500 && offsetX > 40) {
            this.prevPage()
          } else if (time < 500 && offsetX < -40) {
            this.nextPage()
          } else {
            this.toggleTitleAndMenu()
          }
          event.preventDefault()
          event.stopPropagation()
        })
      },
      // 进入上一页
      prevPage () {
        if (this.rendition) {
          this.rendition.prev()
          this.hideTitleAndMenu()
        }
      },
      // 进入下一页
      nextPage () {
        if (this.rendition) {
          this.rendition.next()
          this.hideTitleAndMenu()
        }
      },
      // 点击打开/隐藏title和menu
      toggleTitleAndMenu () {
        if (this.menuVisible) {
          this.setSettingVisible(-1)
        }
        // this.$store.dispatch('setMenuVisible', !this.menuVisible)
        // #TODO 另一种写法
        this.setMenuVisible(!this.menuVisible)
        this.setFontFamilyVisible(false) // 隐藏设置字体页面
      },

      // 翻页时隐藏title和menu
      hideTitleAndMenu () {
        // this.$store.dispatch('setMenuVisible', false)
        this.setMenuVisible(false)
        this.setSettingVisible(-1)
        this.setFontFamilyVisible(false) // 隐藏设置字体页面
      }
    }
  }
</script>

<style scoped>

</style>
